﻿/*!
 * Copyright (c), 上海沃恩信息科技有限公司.
 * All rights reserved.
 * Licensed under BSD (https://www.pittypat.work/bsd.html).
 */

using System;
using System.IO;

namespace Pittypat.Web
{
    /// <summary>
    /// 表示一个要发送给客户端的 <see cref="IUser"/> 值的消息。
    /// </summary>
    sealed class UserMessage : Message
    {
        // 要发送的用户信息
        private IUser user;

        /// <summary>
        /// 使用要发送的 <see cref="IUser"/> 对象初始化 <see cref="UserMessage"/> 类的新实例。
        /// </summary>
        /// <param name="user">要发送的值。可以为 null，此时自动设置为 <see cref="Pittypat.User.Anonymous"/>。</param>
        internal UserMessage(IUser user)
        {
            this.user = user ?? Pittypat.User.Anonymous;
        }

        /// <summary>
        /// 获取消息中包含的值。
        /// </summary>
        public IUser User
        {
            get
            {
                return this.user;
            }
        }

        /// <summary>
        /// 将当前对象作为 JSON 字符串写入指定的文本流。
        /// </summary>
        /// <param name="writer">目标文本流。</param>
        /// <exception cref="ArgumentNullException">writer 是 null。</exception>
        public override void Write(TextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            writer.Write("{\"type\":\"user\",\"info\":");
            this.user.Write(writer);
            writer.Write('}');
        }

        /// <summary>
        /// 将当前对象转换字符串格式
        /// </summary>
        /// <returns>对象的字符串表示形式。</returns>
        public override string ToString()
        {
            using (var writer = new StringWriter())
            {
                this.Write(writer);

                return writer.ToString();
            }
        }
    }
}
